const puppeteer = require('puppeteer')
const base = `https://movie.douban.com/subject/`

const sleep = time => new Promise(resolve => {
  setTimeout(resolve, time)
})

process.on('message', async movies => {
  console.log('start visit the target page')

  const browser = await puppeteer.launch({
    executablePath: '/Users/igolden/Documents/chrome-mac/Chromium.app/Contents/MacOS/Chromium',
    args: ['--no-sandbox'],
    dumpio: false
  })

  const page = await browser.newPage()
  for (let i = 0; i < movies.length; i++) {
    let doubanId = movies[i].doubanId
    await page.goto(base + doubanId, {
      waitUntil: 'networkidle2'
    })

    await sleep(1000)

    const result = await page.evaluate(() => {
      // 在浏览器上执行，所以怕浏览器不支持，建议用var声明
      let $ = window.$
      let it = $('.related-pic-video')
      if (it && it.length > 0) {
        let link = it.attr('href')
        let cover = it.css("background-image").split("\"")[1]
        return {
          link,
          cover
        }
      }
      return {}
    })

    let video
    if (result.link) {
      await page.goto(result.link, {
        waitUntil: 'networkidle2'
      })

      await sleep(2000)

      video = await page.evaluate(() => {
        let $ = window.$
        let it = $('source')

        if (it && it.length > 0) {
          return it.attr('src')
        }
        return ''
      })
    }

    let data = {
      video,
      doubanId,
      cover: result.cover
    }
    // 子进程
    process.send(data)
  }
  
  browser.close()
  process.exit(0)
})